package com.driver.core.convert;

import com.driver.core.Column;
import com.driver.core.DBManager;
import com.driver.core.StringUtil;
import com.driver.core.Table;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractSqlService implements IConvert {

    protected final List<Table> getTable(ICallBack callBack) throws SQLException {
        Connection conn = DBManager.getConn();
        List<Table> tables = new ArrayList<>();
        if (conn == null) throw new RuntimeException("conn为空,可能原因是url、账户、密码、数据库、网络错误");
        DatabaseMetaData dbMetaData = conn.getMetaData();
        ResultSet tabs = dbMetaData.getTables(null, null, DBManager.getConfig().getTable(), new String[]{"TABLE"});
        while (tabs.next()) {
            Table table = new Table();
            table.setTableName((String) tabs.getObject("TABLE_NAME"));

            // 根据表名提前表里面信息：
            ResultSet colRet = dbMetaData.getColumns(null, "%", (String) tabs.getObject("TABLE_NAME"),
                    "%");


            ArrayList<Column> columns = new ArrayList<>();
            while (colRet.next()) {
                Column column = new Column();
                column.setColumnName(colRet.getString("COLUMN_NAME"));
                column.setColumnType(colRet.getString("TYPE_NAME"));
                columns.add(column);
            }


            callBack.getPrivateKey(dbMetaData, columns);//接口回调


            String tableName = table.getTableName();
            if (DBManager.getConfig().getDeleteTableNamePreffix() != null) {
                tableName = StringUtil.getDeleteTableNamePreffix(tableName, DBManager.getConfig().getDeleteTableNamePreffix());
            }

            table.setClassName(StringUtil.tableNameToClassName(tableName));
            table.setColumns(columns);
            tables.add(table);
        }
        conn.close();

        for (Table table : tables) {
            List<Column> columns = table.getColumns();
            for (Column column : columns) {
                column.setPropertyType(columnTypeToJavaType(column.getColumnType()));
                column.setPropertyName(StringUtil.columnNametoPropertyName(column.getColumnName()));
            }
        }
        return tables;
    }

}
